<template>
  <div class="wholesaler-request-container">
    <el-container class="layout-container">
      <el-aside width="220px" class="sidebar">
        <div class="sidebar-content">
          <el-button @click="goBack" class="back-btn">
            <el-icon><ArrowLeft /></el-icon>
            返回主页
          </el-button>
        </div>
      </el-aside>

      <el-main class="main-content">
        <div class="page-header">
          <h1>批发商入场请求</h1>
          <p>处理待确认的批发商产品批号</p>
        </div>

        <!-- 批号列表 -->
        <div class="batch-list">
          <div v-if="loading" class="loading-container">
            <el-icon class="loading-icon"><Loading /></el-icon>
            <span>加载中...</span>
          </div>

          <div v-else-if="batchList.length === 0" class="empty-container">
            <el-empty description="暂无待确认的批发商入场请求" />
          </div>

          <div v-else class="batch-cards">
            <el-card
              v-for="batch in batchList"
              :key="batch.wbId"
              class="batch-card"
              shadow="hover"
            >
              <template #header>
                <div class="card-header">
                  <span class="batch-id">批号: {{ batch.batchId }}</span>
                  <el-tag
                    :type="getStatusTagType(batch.state)"
                    class="status-tag"
                  >
                    {{ getStatusText(batch.state) }}
                  </el-tag>
                </div>
              </template>

              <div class="batch-info">
                <div class="info-item">
                  <span class="label">批发商编号:</span>
                  <span class="value">{{ batch.wholId }}</span>
                </div>
                <div class="info-item">
                  <span class="label">屠宰企业进场编号:</span>
                  <span class="value">{{ batch.sbId }}</span>
                </div>
                <div class="info-item">
                  <span class="label">产品品种:</span>
                  <span class="value">{{ batch.type }}</span>
                </div>
                <div class="info-item">
                  <span class="label">录入日期:</span>
                  <span class="value">{{ formatDate(batch.batchDate) }}</span>
                </div>
                <div class="info-item" v-if="batch.remarks">
                  <span class="label">备注:</span>
                  <span class="value">{{ batch.remarks }}</span>
                </div>
              </div>

              <!-- 操作按钮 -->
              <div class="action-buttons">
                <el-button
                  type="success"
                  size="small"
                  @click="confirmRequest(batch)"
                  class="action-btn"
                >
                  <el-icon><Check /></el-icon>
                  确认请求
                </el-button>
                <el-button
                  type="info"
                  size="small"
                  @click="viewDetails(batch)"
                  class="action-btn"
                >
                  <el-icon><View /></el-icon>
                  详情
                </el-button>
              </div>
            </el-card>
          </div>
        </div>
      </el-main>
    </el-container>
  </div>
</template>

<script>
import { ref, reactive, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { useTokenStore } from "@/stores/token.js";
import { useRouter } from "vue-router";
import { ArrowLeft, Check, Loading, View } from "@element-plus/icons-vue";

export default {
  name: "WholesalerRequest",
  components: {
    ArrowLeft,
    Check,
    Loading,
    View,
  },
  setup() {
    const router = useRouter();
    const tokenStore = useTokenStore();
    const batchList = ref([]);
    const loading = ref(false);

    // 状态映射
    const statusMap = {
      1: "新建",
      2: "待确认",
      3: "已确认",
      4: "已下架",
    };

    // 状态标签类型
    const statusTagType = {
      1: "primary",
      2: "warning",
      3: "success",
      4: "info",
    };

    // 获取状态文本
    const getStatusText = (state) => {
      return statusMap[state] || "未知状态";
    };

    // 获取状态标签类型
    const getStatusTagType = (state) => {
      return statusTagType[state] || "info";
    };

    // 格式化日期
    const formatDate = (dateString) => {
      if (!dateString) return "-";
      try {
        const date = new Date(dateString);
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, "0");
        const day = String(date.getDate()).padStart(2, "0");
        return `${year}-${month}-${day}`;
      } catch (e) {
        console.error("日期格式化错误:", e);
        return dateString;
      }
    };

    // 返回主页
    const goBack = () => {
      router.push("/ent/slaghter");
    };

    // 获取 token
    const getToken = () => {
      return tokenStore.token;
    };

    // 带认证的请求函数
    const requestWithAuth = async (url, options = {}) => {
      const token = getToken();
      const headers = {
        "Content-Type": "application/json",
        ...options.headers,
      };

      if (token) {
        headers["Authorization"] = token;
      }

      const response = await fetch(url, {
        ...options,
        headers,
      });

      if (response.status === 401) {
        ElMessage.error("登录已过期，请重新登录");
        tokenStore.removeToken();
        window.location.href = "/login";
        throw new Error("认证失败");
      } else if (response.status === 403) {
        ElMessage.error("权限不足，无法访问该资源");
        throw new Error("权限不足");
      } else if (!response.ok) {
        throw new Error(`HTTP错误! 状态码: ${response.status}`);
      }

      return response;
    };

    // 加载批发商批号列表
    const loadBatchList = async () => {
      loading.value = true;
      try {
        const response = await requestWithAuth(
          "http://localhost:8080/api/wholBatch/listByState?state=2"
        );

        const responseText = await response.text();

        if (!responseText.trim()) {
          throw new Error("服务器返回空响应");
        }

        let data;
        try {
          data = JSON.parse(responseText);
        } catch (parseError) {
          console.error("JSON解析错误:", parseError);
          throw new Error("服务器返回的数据格式不正确");
        }

        if (Array.isArray(data)) {
          batchList.value = data;
        } else if (data.data && Array.isArray(data.data)) {
          batchList.value = data.data;
        } else {
          batchList.value = [];
        }

        if (batchList.value.length === 0) {
          ElMessage.info("暂无待确认的批发商入场请求");
        }
      } catch (error) {
        console.error("加载批发商批号列表失败:", error);
        if (
          !error.message.includes("认证失败") &&
          !error.message.includes("权限不足")
        ) {
          ElMessage.error("加载批发商批号列表失败");
        }
        batchList.value = [];
      } finally {
        loading.value = false;
      }
    };

    // 确认请求
    const confirmRequest = async (batch) => {
      try {
        await ElMessageBox.confirm(
          `确定要确认批发商产品批号 "${batch.batchId}" 的入场请求吗？`,
          "确认请求",
          {
            confirmButtonText: "确定确认",
            cancelButtonText: "取消",
            type: "warning",
            confirmButtonClass: "confirm-btn",
          }
        );

        // 调用确认API
        const response = await requestWithAuth(
          `http://localhost:8080/api/wholBatch/confirm/${batch.wbId}`,
          {
            method: "PUT",
          }
        );

        const result = await response.json();

        if (result.success) {
          ElMessage.success("确认成功");
          // 重新加载列表
          loadBatchList();
        } else {
          ElMessage.error(result.message || "确认失败");
        }
      } catch (error) {
        if (error !== "cancel") {
          console.error("确认失败:", error);
          ElMessage.error("确认失败");
        }
      }
    };

    // 查看详情
    const viewDetails = (batch) => {
      ElMessageBox.alert(
        `
            <div style="text-align: left; line-height: 1.8;">
              <p><strong>批发商产品批号:</strong> ${batch.batchId || "-"}</p>
              <p><strong>批发商编号:</strong> ${batch.wholId || "-"}</p>
              <p><strong>屠宰企业进场编号:</strong> ${batch.sbId || "-"}</p>
              <p><strong>产品品种:</strong> ${batch.type || "-"}</p>
              <p><strong>录入日期:</strong> ${formatDate(batch.batchDate)}</p>
              <p><strong>状态:</strong> ${getStatusText(batch.state)}</p>
              <p><strong>备注:</strong> ${batch.remarks || "无"}</p>
            </div>
          `,
        "批发商产品批号详情",
        {
          dangerouslyUseHTMLString: true,
          confirmButtonText: "确定",
          customClass: "detail-dialog",
        }
      );
    };

    // 初始化加载
    onMounted(() => {
      loadBatchList();
    });

    return {
      batchList,
      loading,
      getStatusText,
      getStatusTagType,
      formatDate,
      goBack,
      confirmRequest,
      viewDetails,
    };
  },
};
</script>

<style scoped>
.wholesaler-request-container {
  height: 100vh;
  background: linear-gradient(135deg, #f8fafc 0%, #e2e8f0 100%);
}

.layout-container {
  height: 100%;
}

.sidebar {
  background: linear-gradient(180deg, #2d3748 0%, #1a202c 100%);
  padding: 20px;
  display: flex;
  align-items: flex-start;
}

.sidebar-content {
  width: 100%;
}

.back-btn {
  width: 100%;
  height: 48px;
  border-radius: 8px;
  background: rgba(255, 255, 255, 0.1);
  border: 1px solid rgba(255, 255, 255, 0.2);
  color: white;
  transition: all 0.3s ease;
}

.back-btn:hover {
  background: rgba(255, 255, 255, 0.2);
  transform: translateY(-2px);
}

.back-btn .el-icon {
  margin-right: 8px;
}

.main-content {
  padding: 30px;
  background: transparent;
  overflow-y: auto;
}

.page-header {
  margin-bottom: 30px;
}

.page-header h1 {
  margin: 0 0 8px 0;
  color: #2d3748;
  font-size: 28px;
  font-weight: 600;
}

.page-header p {
  margin: 0;
  color: #718096;
  font-size: 16px;
}

.batch-list {
  min-height: 400px;
}

.loading-container,
.empty-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60px 20px;
  color: #718096;
}

.loading-icon {
  font-size: 32px;
  margin-bottom: 16px;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}

.batch-cards {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(320px, 1fr));
  gap: 20px;
}

.batch-card {
  border-radius: 12px;
  border: none;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  background: rgba(255, 255, 255, 0.95);
  transition: all 0.3s ease;
}

.batch-card:hover {
  transform: translateY(-4px);
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.12);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.batch-id {
  font-weight: 600;
  color: #2d3748;
}

.status-tag {
  font-weight: 500;
}

.batch-info {
  margin-bottom: 16px;
}

.info-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
  padding: 4px 0;
}

.info-item:last-child {
  margin-bottom: 0;
}

.label {
  color: #718096;
  font-size: 14px;
  font-weight: 500;
}

.value {
  color: #2d3748;
  font-size: 14px;
  font-weight: 600;
}

.action-buttons {
  display: flex;
  gap: 8px;
  justify-content: flex-end;
}

.action-btn {
  border-radius: 6px;
  transition: all 0.3s ease;
}

.action-btn:hover {
  transform: translateY(-1px);
}

.action-btn .el-icon {
  margin-right: 4px;
}

@media (max-width: 768px) {
  .sidebar {
    width: 100% !important;
    height: auto;
  }

  .main-content {
    padding: 20px;
  }

  .page-header h1 {
    font-size: 24px;
  }

  .batch-cards {
    grid-template-columns: 1fr;
  }

  .card-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
  }

  .info-item {
    flex-direction: column;
    align-items: flex-start;
    gap: 4px;
  }
}
</style>

<style>
.confirm-btn {
  background-color: #67c23a;
  border-color: #67c23a;
}

.confirm-btn:hover {
  background-color: #5daf34;
  border-color: #5daf34;
}

.detail-dialog {
  min-width: 500px;
}
</style>
